//
//  ChatViewController.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "ChatViewController.h"

#import "TZImagePickerController.h"
#import "SearchBusinessCardVC.h"
#import "FriendChatSettingVC.h"
#import "GroupSetViewController.h"
#import "StartGroupChatVC.h"
#import "ChatWebViewController.h"

#import "BTChatBar.h"
#import "MessageCell.h"
#import "MessageTipsCell.h"
//#import "GroupNoticeView.h"

#import "BTMessageModel.h"
#import "TextMessageModel.h"
#import "VoiceMessageModel.h"
#import "ImageMessageModel.h"

#import "ChatTool.h"
#import "AudioPlayerHelper.h"
#import "MWPhotoBrowser.h"
#import "UIImage+Compress.h"
#import "AudioRecordAnimateView.h"
#import "ContactModel.h"
#import "ContactRequestLogic.h"

#import "NSString+DictionaryValue.h"
@interface ChatViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate,BTChatBarDelegate,MessageCellDelegate,TZImagePickerControllerDelegate,LiftIMChatMangerDelegate,GroupSetViewControllerDelegate,FriendChatSettingVCDelegate,MessageTipsCellDelegate>
@property(nonatomic, strong) UITableView *chatTableView;
@property (nonatomic, strong) BTChatBar *chatBar;
@property(nonatomic, strong) NSMutableArray<BTMessageModel *> *dataSources;
@property(nonatomic, strong) NSMutableDictionary* selectedUserData; //@选中好友
//长按操作栏
@property (strong, nonatomic) NSIndexPath *menuIndexPath;
@property (nonatomic, strong) UIMenuController *menuController;
@property (nonatomic, strong) UIMenuItem *recallMenuItem;
@property (nonatomic, strong) UIMenuItem *textCopyMenuItem;

// 录音
@property (nonatomic, strong) AudioRecordAnimateView *recordAnimateView;
@property(nonatomic, strong)NSDictionary * groupSetData;//群设置数据
@property(nonatomic, assign) BOOL isForbid; // 群聊是否被禁言
@property(nonatomic, assign) BOOL isOwnerOrManager;

@property(nonatomic, assign) NSInteger atType; // @类型  1：单人和多人  2：所有人
@property(nonatomic, strong) NSMutableArray *atIds;
@property(nonatomic, copy) NSString *originSendText;

@property(nonatomic, assign) long long lastRefreshTime;  // 上一次刷新时间
@property(nonatomic, assign) long long lastReceiveMsgTime; // 上一次接收到消息的时间
@property(nonatomic, assign) long long lastMiniteBeginSeconds; // 上次发送消息的起始秒数，毫秒
@property(nonatomic, assign) NSInteger currentSendCount;

// 离线消息相关
@property(nonatomic, assign) NSInteger requestPageIndex; // 请求页码
@property(nonatomic, assign) BOOL haveOfflineMessage;
@property(nonatomic, assign) BOOL deleteOfflineMessageFinished; // 删除离线操作是否结束
@property(nonatomic, assign) BOOL isScrollBottom;

@property(nonatomic, strong) UIButton *unreadCountBtn;
@property(nonatomic, assign) NSInteger unreadCount;
@property(nonatomic, assign) BOOL isInit;
@property(nonatomic, assign) BOOL isTouch; // 是否正在滚动

@property (nonatomic,strong)ContactModel * friendModel;
@property(nonatomic,copy)NSString * markGroupHead,* markGroupName;

@property(nonatomic,strong)CustomAlertView  * addFriensAlertView;
@end

@implementation ChatViewController
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[ChatTool shareChatTool] requestSeverTime];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[AudioPlayerHelper shareAudioPlayerHelper] stopPlayer];
    [_recordAnimateView dismiss];

}
-(void)dealloc
{
    [[LiftIMClient sharedClient].chatManager removeDelegate:self];
}

//代理修改群展示名称
- (void)refreshGroupTitle:(NSString *)title{
    self.gk_navTitle = title;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [[LiftIMClient sharedClient].chatManager addDelegate:self];

    [self setupSubviews];
    
    self.haveOfflineMessage = YES;
    self.deleteOfflineMessageFinished = YES;
    self.isScrollBottom = YES;
    self.isInit = YES;
    self.requestPageIndex = 0;
    [self loadDataFromDB];
    if (self.destinationTimestamp) {
        [self.dataSources removeAllObjects];
        [self loadAllDataFromDB];
    } else {
        [self loadDataFromDB];
    }
    
    if (_chatType == ChatTypeFriend) {
        [ContactRequestLogic requestSearchFriendResultsWithfuuid:[NSString stringWithFormat:@"%@",_receiverId] Success:^(NSDictionary * _Nonnull Dict) {
            KWeakSelf;
           NSLog(@"好友信息%@",Dict[@"data"]);
           weakSelf.friendModel = [ContactModel mj_objectWithKeyValues:Dict[@"data"]];
            weakSelf.gk_navTitle = weakSelf.friendModel.nickname;
        } failure:^(NSString * _Nonnull errMsg) {
            NSLog(@"%@",errMsg);
            [self hideHud];
            [self showTipHudWithText:@"网络错误，请重试"];
        }];
    }else if (_chatType == ChatTypeGroup)
    {
        [self fetchForbidStatus];//获取群禁言状态
    }
    // Do any additional setup after loading the view.
}
-(void)fetchForbidStatus
{
    KWeakSelf;
    [ContactRequestLogic  requestShowGroupSetWithGroupid:_receiverId Success:^(NSDictionary * _Nonnull Dict) {
        AAIMLog(@"群设置数据=%@",Dict);
        NSLog(@"群title=====%@",self.gk_navTitle);
        weakSelf.markGroupHead= [NSString stringWithFormat:@"%@",Dict[@"data"][@"groupHead"]];
        weakSelf.markGroupName= [NSString stringWithFormat:@"%@",Dict[@"data"][@"groupName"]];

        if (![NSObject ldy_isEmpty:self.gk_navTitle]) {
            if (![self.gk_navTitle isEqualToString:Dict[@"data"][@"groupName"]]) {
                self.gk_navTitle=Dict[@"data"][@"groupName"];
                [[UserDataBaseTool shareUserDataBaseTool] reloadData:2 Success:^(BOOL isOK) {
                    if (isOK) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
                    }
                }];
            }
        }
        weakSelf.groupSetData=Dict[@"data"];
        weakSelf.isForbid= ![weakSelf.groupSetData[@"isChat"] boolValue];
        weakSelf.isOwnerOrManager=[weakSelf.groupSetData[@"isMaster"] boolValue];
        if (!weakSelf.isOwnerOrManager) {
            weakSelf.chatBar.forbid = weakSelf.isForbid;
            if ( weakSelf.isForbid) {
                weakSelf.chatBar.textView.placeholder=@"禁言";
                weakSelf.chatBar.textView.placeholderColor=KHEXCOLOR(kBlackColor);
            }
        }
        
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"群资料请求错误=%@",errMsg);
        
        [ContactRequestLogic requestCheckGroupNameWithGroupID:weakSelf.receiverId Success:^(NSDictionary * _Nonnull Dict) {
            weakSelf.markGroupHead= [NSString stringWithFormat:@"%@",Dict[@"data"][@"groupHead"]];
            weakSelf.markGroupName= [NSString stringWithFormat:@"%@",Dict[@"data"][@"groupName"]];
            self.gk_navTitle=weakSelf.markGroupName;
            
        } failure:^(NSString * _Nonnull errMsg) {
            NSLog(@"-------:%@",errMsg);
        }];
    }];
    
    
}
-(void)setupSubviews
{
    // 导航右按钮
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(rightBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    [rightBtn setImage:[UIImage imageNamed:@"icon- 点点"] forState:UIControlStateNormal];
    [rightBtn setTitleColor:KHEXCOLOR(AllBackColor_titleColor) forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    rightBtn.jk_touchAreaInsets = UIEdgeInsetsMake(20, 20, 20, 20);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    if (self.chatType == ChatTypeFriend) {
        self.gk_navigationItem.rightBarButtonItem = rightItem;
    }else
    {
        BOOL isMember = [[UserDataBaseTool shareUserDataBaseTool] isGroupMembersWithgId:[self.receiverId integerValue]];
        if (isMember) {
            self.gk_navigationItem.rightBarButtonItem = rightItem;
        }
    }
    // 视图
    self.chatBar = [[BTChatBar alloc] init];
    self.chatBar.delegate = self;
    [self.view addSubview:self.chatBar];
    [self.chatBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    self.chatTableView.backgroundColor = KHEXCOLOR(kGrayColor_f2);
    self.chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.chatTableView.rowHeight = UITableViewAutomaticDimension;
    self.chatTableView.estimatedRowHeight = 130;
    [self.chatTableView registerClass:[MessageTipsCell class] forCellReuseIdentifier:[MessageTipsCell cellIdentifier]];
    [self.view addSubview:self.chatTableView];
    [self.chatTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.gk_navigationBar.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.chatBar.mas_top);
    }];
    
    self.chatTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNormalHeaderAction)];
}
-(void)refreshNormalHeaderAction
{
    _requestPageIndex ++;
    [self loadDataFromDB];
    [self requestData];
//    [self.chatTableView.mj_header endRefreshing];
}
// 请求离线消息
- (void)requestData {
    /*
    if (self.haveOfflineMessage && self.deleteOfflineMessageFinished) {
        NSLog(@"分页加载开始");
        [[NetworkTool shareInstance] offlineMessagesWithUid:[LoginManager shareLoginManager].userModel.user_id.integerValue type:self.type uidOrGroupId:self.receiverId pageIndex:0 pageSize:100 completed:^(SLResultModel * _Nonnull res) {
            NSLog(@"分页加载完成");
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                if (res.isSuccess) {
                    NSArray<BTMessageModel *> *messages = [BTMessageModel mj_objectArrayWithKeyValuesArray:res.rawdata[@"obj"]];
                    [messages enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        obj.messageDirection  = MessageDirectionReceive;
                    }];
                    if (messages == nil || messages.count == 0) {
                        self.haveOfflineMessage = NO;
                    } else {
                        [self deleteOfflineMessage:messages];
                        if ([self.type isEqualToString:@"friend"]) {
                            [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessagArray:messages];
                        } else {
                            [[GroupMessageDataBase shareGroupMessageDataBase] insertMessagArray:messages];
                        }
                    }
                } else {
                    self.haveOfflineMessage = NO;
                }
            });
        }];
    }
     */
}
// 获取所有数据
- (void)loadAllDataFromDB {
    NSArray *messages = [NSArray new];
    if (_chatType==ChatTypeFriend) {
        messages = [[ChatMessagesDataBase shareChatMessagesDataBase] queryAllMessagesWithUid:[self.receiverId integerValue]];
    } else {
        messages = [[GroupMessageDataBase shareGroupMessageDataBase] queryAllMessagesWithGroupId:[self.receiverId integerValue]];
    }
    if (messages.count) {
        [self.dataSources addObjectsFromArray:messages];
        [self.chatTableView reloadData];
        [self scrollToDestinationTimestamp];
    }
}

// 从数据库获取消息
- (void)loadDataFromDB {
    NSInteger originCount = self.dataSources.count;
    NSArray *messages = [NSArray new];
    NSInteger count = (_requestPageIndex + 1) * 20;
    if (_chatType==ChatTypeFriend) {
        messages = [[ChatMessagesDataBase shareChatMessagesDataBase] queryMessagesWithUid:[self.receiverId integerValue] count:count];
    } else {
        messages = [[GroupMessageDataBase shareGroupMessageDataBase] queryMessagesWithGroupId:[self.receiverId integerValue] count:count];
    }
    if (messages.count == 0) {
        [self.dataSources removeAllObjects];
        [self.chatTableView reloadData];
        [self.chatTableView.mj_header endRefreshing];
        return;
    } else if (messages.count <= self.dataSources.count) {
        if (self.chatTableView.mj_header.isRefreshing) {
            [self showTipHudWithText:@"没有更多数据了"];
        }
        [self.chatTableView.mj_header endRefreshing];
    }
    
    [self.dataSources removeAllObjects];
    [messages enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.messageStatus == MessageStatusDelivering) {
            obj.messageStatus = MessageStatusFailed;
        }
        [self.dataSources addObject:obj];
    }];
    [self.chatTableView reloadData];
    if (self.requestPageIndex == 0) {
        [self performSelector:@selector(scrollToBottomRow) withObject:nil afterDelay:0.2];
    } else {
        NSInteger row = self.dataSources.count - originCount + [[self.chatTableView visibleCells] count] - 2;
        if (row >= self.dataSources.count) {
            row = self.dataSources.count - [[self.chatTableView visibleCells] count] - 2;
        }
        if (row < 0) {
            row = 0;
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
    [self.chatTableView.mj_header endRefreshing];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSources.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSources.count <= indexPath.row) {
        MessageTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:[MessageTipsCell cellIdentifier]];
        return cell;
    }
    BTMessageModel *model = self.dataSources[indexPath.row];
    if (model.chatType == ChatTypeFriend || model.chatType == ChatTypeGroup) {
        if (model.msgtype == MessageTypeText || model.msgtype == MessageTypeImage || model.msgtype == MessageTypeVoice) {
            NSString *identifier = [MessageCell cellIdentifierWithDirection:model.messageDirection type:model.msgtype];
            MessageCell *cell = (MessageCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[MessageCell alloc] initWithDirection:model.messageDirection type:model.msgtype];
            }
            cell.model = model;
            cell.delegate = self;
            return cell;
        } else if (model.msgtype == MessageTypeRecall || model.msgtype == MessageTypeTime||model.msgtype == MessageTypeInviteAddGroup ||model.msgtype == MessageTypeMangerDeleteMember ||model.msgtype == MessageTypeGroupDissolution ||model.msgtype == MessageTypeStartGroupChatting ||model.msgtype == MessageTypeAddedBlacklist ||model.msgtype == MessageTypeNotInGroup ||model.msgtype == MessageTypeNotFriend ||model.msgtype == MessageTypeSendFailure ||model.msgtype == MessageTypeSendBanned) {
            MessageTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:[MessageTipsCell cellIdentifier]];
            cell.message = model;
            cell.delegate=self;
            return cell;
        } else if(model.type_id == SystemMessageAuditJoinGroup || model.type_id == SystemMessageDeleteGroupMember || model.type_id == SystemMessageMemberExit || model.type_id == SystemMessageDeleteGroup){
            MessageTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:[MessageTipsCell cellIdentifier]];
            cell.message = model;
            cell.delegate=self;
            return cell;
        }else
        {
            return nil;
        }
    }else
    {
        if ( model.type_id == SystemMessageAuditJoinGroup || model.type_id == SystemMessageDeleteGroupMember || model.type_id == SystemMessageMemberExit || model.type_id == SystemMessageDeleteGroup) {
            MessageTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:[MessageTipsCell cellIdentifier]];
            cell.message = model;
            cell.delegate=self;
            return cell;
        } else {
            return nil;
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = cell.frame.size.height;
    BTMessageModel *model = self.dataSources[indexPath.row];
    model.cellHeight = height;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BTMessageModel *model = self.dataSources[indexPath.row];
    if (model.cellHeight > 10) {
        return model.cellHeight;
    } else {
        return 130;
    }
}
#pragma mark - MessageCellDelegate
// 点击
- (void)messageCellDidSelected:(MessageCell *)cell {
    if (cell.model.msgtype == MessageTypeText) {
        
    } else if (cell.model.msgtype == MessageTypeImage) {
        [self imageMesssageCellDidSelected:cell];
    } else if (cell.model.msgtype == MessageTypeVoice) {
        [self voiceMessageCellDidSelected:cell];
    }
}

// 重发
- (void)messageCellDidResend:(BTMessageModel *)model {
   
    if (self.chatType ==ChatTypeFriend) {
        [[ChatMessagesDataBase shareChatMessagesDataBase] deleteMessage:model];
    } else {
        [[GroupMessageDataBase shareGroupMessageDataBase] deleteMessage:model];
    }
    if (model.msgtype == MessageTypeText) {
        [self sendTextMessage:model.msg];
    } else if (model.msgtype == MessageTypeImage) {
        ImageMessageModel *imageModel = (ImageMessageModel *)model;
        [self sendImageMessage:imageModel.image];
    } else if (model.msgtype == MessageTypeVoice) {
        VoiceMessageModel *voiceModel = (VoiceMessageModel *)model;
        [self sendVoiceMessage:voiceModel.path timeLength:voiceModel.duration];
    }
    // 刷新界面
    [self.dataSources removeObject:model];
    [self.chatTableView reloadData];
}

// 长按
- (void)messageCellDidLongPress:(MessageCell *)cell {
    self.menuIndexPath = [self.chatTableView indexPathForCell:cell];
    [self showMenuViewController:cell model:cell.model];
    
}
//点击头像
-(void)didSelecedUserHead:(MessageCell *)cell
{
}

// URL点击
- (void)messageCellDidClickUrl:(NSString *)url {
    ChatWebViewController * vc=[[ChatWebViewController alloc]init];
    NSString *urlStr = [url containsString:@"http:"] ? url : [NSString stringWithFormat:@"http://%@", url];
    vc.urlStr = urlStr;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark  messageTipCellDelegate
-(void)messageTipsCellDidSelected:(MessageTipsCell *)cell
{
    NSLog(@"对方的id=%@",cell.message.rfuuid);

    KWeakSelf;
        _addFriensAlertView=[[CustomAlertView alloc]initWithFrame:self.view.bounds withType:@"8" title:[LoginManager shareLoginManager].userModel.nickname];
        
        _addFriensAlertView.clickBlock = ^(NSString * _Nonnull selectType, NSString * _Nonnull textf, NSString * _Nonnull remarkStr) {
            if ([selectType isEqualToString:@"2"]) {
                //source ，s 搜索  g群
                [ContactRequestLogic  requestAddFriendWithContent:textf fuuid:cell.message.rfuuid groupid:@"" source:@"s" Success:^(NSDictionary * _Nonnull Dict) {
                    //申请成功发送im消息
                    NSLog(@"发送请求%@",Dict);
                    if ([Dict[@"code"] integerValue] == 200) {
                        if (![CommonTools isNull:Dict key:@"data"]) {
                            NSString * addStatu = [NSString stringWithFormat:@"%@",Dict[@"data"][@"add"]];
                            if ([addStatu isEqualToString:@"1"]) {
//                                [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
//                                    if (isOK) {
//                                        [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
//                                    }
//                                }];
                            }
                        }else{
                            [weakSelf showTipHudWithText:Dict[@"message"]];
                        }
                    }
                    
                } failure:^(NSString * _Nonnull errMsg) {
                    [weakSelf showTipHudWithText:errMsg];
                }];
            }
            [weakSelf.addFriensAlertView removeFromSuperview];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:_addFriensAlertView];

    
}
#pragma mark -- UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    [self.chatTableView reloadData];
    [self.chatBar clearMoreViewAndSelectedButton];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint point = [scrollView.panGestureRecognizer translationInView:scrollView];
    CGFloat offsetY = point.y;
    if (offsetY < 0) {
        //        NSLog(@"下滑");
        
    } else {
        //        NSLog(@"上滑");
        if (self.isInit) {
            self.isInit = NO;
        } else {
            self.isScrollBottom = NO;
        }
    }
    
    // 判断滚到到最后
    if (self.dataSources.count == 0) return;
    CGFloat delta = scrollView.contentSize.height - scrollView.contentOffset.y;
    if (delta < scrollView.height + 3) {
        self.unreadCountBtn.hidden = YES;
        self.unreadCount = 0;
        self.isScrollBottom = YES;
    }
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.isTouch = YES;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.isTouch = NO;
}

#pragma mark - BTChatBarDelegate

- (void)chatBarForbidBtnDidClickAction {
    [self showTipHudWithText:@"群已经开启禁言"];
}
-(BOOL)inputView:(UITextView *)inputView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text userIdsArray:(NSMutableArray *)userIdsArray
{
    self.atIds = userIdsArray;
    if ([text isEqualToString:@"\n"]) { // 回车发送
        [self sendTextMessage:inputView.text];
        return NO;
    } else if ([text isEqualToString:@"@"]) { // @他人
        [self sendAtMessage:inputView];
    } else if ([text length] == 0) {
        
    }
    return YES;
}
- (void)sendAtMessage:(UITextView *)inputView {
    NSLog(@"发送@消息");
    KWeakSelf;
    StartGroupChatVC * vc =[[StartGroupChatVC alloc]init];
    vc.groupID=self.receiverId;
    vc.type=5;
    vc.selectedSuccessBlcok = ^(NSString * _Nonnull type, NSString * _Nonnull nickName, NSString * _Nonnull userid) {
        [weakSelf.chatBar.textView becomeFirstResponder];
        weakSelf.atType = 1;
        if ([type isEqualToString:@"1"]) {
            //单个选中@
            if ([NSObject ldy_isEmpty:inputView.text]) {
                inputView.text=nickName;
            }else
            {
                inputView.text=[NSString stringWithFormat:@"%@%@ ",inputView.text,nickName];
            }
            
        }else
        {
            weakSelf.atType = 2;
            if ([NSObject ldy_isEmpty:inputView.text]) {
                inputView.text=@"所有人";
            }else
            {
                inputView.text=[NSString stringWithFormat:@"%@所有人",inputView.text];
            }
        }
        //传userid
        [weakSelf.selectedUserData setObject:nickName forKey:userid];
        [weakSelf.chatBar selectedUserWith:weakSelf.selectedUserData Type:type.integerValue];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)chatBarRecordAudioViewStartRecord {
    _recordAnimateView = [[AudioRecordAnimateView alloc] init];
    _recordAnimateView.tips = @"松开发送录音";
    [_recordAnimateView show];
}

- (void)chatBarRecordAudioViewStopRecord:(NSString *)path timeLength:(NSInteger)timeLength {
    if (timeLength < 1.0) {
        [_recordAnimateView dismiss];
        [self showTipHudWithText:@"录音时间太短"];
        return;
    }
    [self sendVoiceMessage:path timeLength:timeLength];
    [_recordAnimateView dismiss];
}
-(void)chatCountdownAnimationWithTime:(NSInteger)time
{
    _recordAnimateView.tips=[NSString stringWithFormat:@"%ld",time];
}
- (void)chatBarRecordAudioViewCancelRecord {
    [_recordAnimateView dismiss];
}

- (void)chatBarDidShowMoreViewAction {
    [self.chatTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.chatBar.mas_top);
    }];
    [self.chatTableView reloadData];
    [self performSelector:@selector(scrollToBottomRow) withObject:nil afterDelay:0.1];
}

- (void)chatBarPhotoBtnDidClickAction {
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    picker.allowPickingVideo = NO;
    picker.allowPickingOriginalPhoto = NO;
    picker.allowCrop = NO;
    picker.maxImagesCount= 9;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)chatBarCameraBtnDidClickAction {
    UIImagePickerController *picker = [UIImagePickerController new];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = NO;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)chatBarBusinessCardDidClickAction
{
    SearchBusinessCardVC* vc=[[SearchBusinessCardVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    image = [image compressSizeOfImageData:image maxSize:100];
    [self sendImageMessage:image];
}
#pragma mark -- TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    //上传照片
    [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *compressedImage = [obj compressSizeOfImageData:obj maxSize:100];
        [self sendImageMessage:compressedImage];
    }];
}

#pragma mark - private methods

- (void)scrollToBottomRow {
    [self.chatTableView reloadData];
    if (self.dataSources.count > 0) {
        NSInteger toRow = self.dataSources.count - 1;
        NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:toRow inSection:0];
        [self.chatTableView scrollToRowAtIndexPath:toIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

- (void)scrollToDestinationTimestamp {
    __block NSInteger toRow = 0;
    [self.dataSources enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.timestamp == self.destinationTimestamp) {
            toRow = idx;
            *stop = YES;
        }
    }];
    NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:toRow inSection:0];
    [self.chatTableView scrollToRowAtIndexPath:toIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}

- (void)showMenuViewController:(MessageCell *)cell
                         model:(BTMessageModel *)model {
    [self becomeFirstResponder];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    // 复制
    if (model.msgtype == MessageTypeText) {
        [items addObject:self.textCopyMenuItem];
    }
//    // 撤回
//    if (model.messageDirection == MessageDirectionSend) {
//        [items addObject:self.recallMenuItem];
//    } else {
//        if (self.isOwnerOrManager) {
//            [items addObject:self.recallMenuItem];
//        }
//    }
    [self.menuController setMenuItems:items];
    if (items.count) {
        [self.menuController setTargetRect:cell.bubbleView.frame inView:cell];
        [self.menuController setMenuVisible:YES animated:NO];
    }
}

// 消息撤回
- (void)recallMenuItemAction:(UIMenuItem *)item {
    if (self.menuIndexPath == nil) {
        return;
    }
    NSIndexPath *indexPath = self.menuIndexPath;
    [self sendRecallMessage:indexPath];
}

// 消息复制
- (void)textCopyMenuItemAction:(UIMenuItem *)item {
    if (self.menuIndexPath == nil) {
        return;
    }
    NSIndexPath *indexPath = self.menuIndexPath;
    TextMessageModel *textModel = (TextMessageModel *)self.dataSources[indexPath.row];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = textModel.msg;
    [self showTipHudWithText:@"复制成功"];
}

// 数据源截取前n条数据
- (void)sliceDataSources {
  
}

// 判断是否在数据源中加入时间
- (void)addTimeMessageBefore:(BTMessageModel *)msg {
    BTMessageModel *timeMsg = [BTMessageModel new];
    timeMsg.messageDirection = MessageDirectionSend;
    timeMsg.msgtype = MessageTypeTime;
    timeMsg.uid = [[LoginManager shareLoginManager].userModel.fuuid integerValue];
    //    long long timestamp =  [ChatTool shareChatTool].currentTimestamp;
    timeMsg.timestamp = msg.timestamp;
    timeMsg.cid = msg.timestamp;
    timeMsg.mine = YES;
    timeMsg.msgtype = MessageTypeTime;
    timeMsg.username = [LoginManager shareLoginManager].userModel.nickname;
    timeMsg.rfuuid =timeMsg.gId = self.receiverId;
//    timeMsg.type = self.type;
    if (self.dataSources.count) {
        BTMessageModel *lastMsg = [self.dataSources lastObject];
        if (msg.timestamp - lastMsg.timestamp > 1 * 60 * 1000) {
            [self.dataSources addObject:timeMsg];
            if (msg.messageDirection == MessageDirectionSend) {
                if (msg.chatType == ChatTypeFriend) {
                    [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:timeMsg];
                } else {
                    [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:timeMsg];
                }
            }
        }
    } else {
        [self.dataSources addObject:timeMsg];
        if (msg.messageDirection == MessageDirectionSend) {
            if (msg.chatType == ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:timeMsg];
            } else {
                [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:timeMsg];
            }
        }
    }
}
-(void)addChatStateBefore:(BTMessageModel*)msg msgtype:(NSInteger)msgtype
{
    NSString * messageText;
    BTMessageModel * textModel= [BTMessageModel new];
//    textModel=msg;
    textModel.messageDirection = MessageDirectionSend;
    textModel.msgtype=msgtype;
    textModel.chatType=msg.chatType;
    textModel.uid = [[LoginManager shareLoginManager].userModel.fuuid integerValue];
    switch (textModel.msgtype) {
        case MessageTypeInviteAddGroup:
            messageText= [NSString stringWithFormat:@" ”%@“邀请了”%@“加入群聊",@"群主",msg.username];
            break;
        case MessageTypeMangerDeleteMember:
            messageText= [NSString stringWithFormat:@" ”群主“将”%@“移除了群聊",msg.username];
            break;
        case MessageTypeGroupDissolution:
            messageText= @"该群已解散";
            break;
        case MessageTypeStartGroupChatting:
            messageText= [NSString stringWithFormat:@"”%@“发起群聊",msg.username];
            break;
        case MessageTypeAddedBlacklist:
            messageText= @"对方已经将你加入黑名单";
            break;
        case MessageTypeNotInGroup:
            messageText= @"您已经不在群里";
            break;
        case MessageTypeNotFriend:
            messageText= @"对方已将您删除，请重新添加好友";
            break;
        case MessageTypeSendFailure:
            messageText= @"发送失败";
            break;
        case MessageTypeSendBanned:
            messageText= @"本群已禁言";
            break;
        default:
            break;
    }
    textModel.msg=messageText;
        long long timestamp =  [ChatTool shareChatTool].currentTimestamp;
    textModel.timestamp = timestamp;
    textModel.cid = timestamp;
    textModel.mine = YES;
//    textModel.username = [LoginManager shareLoginManager].userModel.nickname;
    textModel.rfuuid =textModel.gId = self.receiverId;
    textModel.rfuuid =  self.receiverId;
    textModel.chatType = self.chatType;
    textModel.gId = self.receiverId;
    textModel.type_id=1111111;
    if (self.chatType == ChatTypeFriend) {
        textModel.head = [LoginManager shareLoginManager].userModel.head;
        textModel.username = [LoginManager shareLoginManager].userModel.nickname;
    }else
    {
        textModel.groupHead= self.markGroupHead;
        textModel.groupName= self.markGroupName;
    }
    [self.dataSources addObject:textModel];
    [self scrollToBottomRow];
    //存储数据
    [[ConversationListDataBase shareConversationListDataBase] saveConversation:textModel];
    [[ConversationManager shareManager] saveConversation:textModel];
    
    if (msg.messageDirection == MessageDirectionSend) {
        if (msg.chatType == ChatTypeFriend) {
            [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:textModel];
        } else {
            [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:textModel];
        }
    }
}
#pragma mark - 单元格点击

// 图片单元格点击
- (void)imageMesssageCellDidSelected:(MessageCell *)cell {
    ImageMessageModel  *imageMessage = (ImageMessageModel *)cell.model;
    
    UIImage *image = nil;
    if (cell.messageDirection == MessageDirectionSend) {
        image = imageMessage.image;
    } else {
        NSString *fileName = imageMessage.path.lastPathComponent;
        NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        doucument = [doucument stringByAppendingPathComponent:kMessageImageFileName];
        NSString *fullpath = [doucument stringByAppendingPathComponent:fileName];
        image = [UIImage imageWithData:[NSData dataWithContentsOfFile:fullpath options:NSDataReadingMappedIfSafe error:nil]];
    }
    MWPhoto *photo;
    if (image) {
        photo = [[MWPhoto alloc] initWithImage:image];
    } else {
        photo = [[MWPhoto alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",LIFT_APP_USER_PIC_KEY,imageMessage.msg]]];
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithPhotos:@[photo]];
    
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    browser.enableSwipeToDismiss = NO;
    browser.autoPlayOnAppear = YES;
    
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [browser setCurrentPhotoIndex:0];
    
    [self.navigationController pushViewController:browser animated:YES];
    
}
// 语音单元格点击
- (void)voiceMessageCellDidSelected:(MessageCell *)cell {
    WS(ws);
    VoiceMessageModel *voiceMessage = (VoiceMessageModel *)cell.model;
    long long time = 0;
    if (voiceMessage.messageDirection == MessageDirectionSend) {
        NSString *fileName = voiceMessage.path.lastPathComponent;
        time = [[fileName componentsSeparatedByString:@"."][0] longLongValue];
    } else {
        time = voiceMessage.timestamp;
    }
    NSString *fileName = [NSString stringWithFormat:@"%lld.wav",time];
    NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    doucument = [doucument stringByAppendingPathComponent:kMessageVoiceFileName];
    NSString *fullpath = [doucument stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:fullpath];
    if (!result) {
//        [self showAlwaysTipHudWithText:@"正在下载语音"];
        [[NetWorkTool shareInstance]downloadVoiceFile:voiceMessage.msg targetPath:fullpath progress:nil completion:^(NSError * _Nonnull error) {
            if (!error) {
                // 语音完成下载
                voiceMessage.path = fullpath;
                [self.chatTableView reloadData];
                // 播放
                [[AudioPlayerHelper shareAudioPlayerHelper] startPlayerWithPath:fullpath model:voiceMessage completion:^(NSError * _Nonnull error) {
                    voiceMessage.isPlaying = NO;
                    [ws.chatTableView reloadData];
                }];
                voiceMessage.isPlaying = YES;
                [self.chatTableView reloadData];
            }
//            [self hideHud];
        }];
        return;
    }
    
    if (voiceMessage.isPlaying) { // 该语音正在播放
        [[AudioPlayerHelper shareAudioPlayerHelper] stopPlayer];
        voiceMessage.isPlaying = NO;
        [self.chatTableView reloadData];
        return;
    } else { // 该语音不在播放
        // 暂停其他语音播放
        [self.dataSources enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.msgtype == MessageTypeVoice) {
                VoiceMessageModel *voiceMsg = (VoiceMessageModel *)obj;
                if (voiceMsg.isPlaying) {
                    voiceMsg.isPlaying = NO;
                    [[AudioPlayerHelper shareAudioPlayerHelper] stopPlayer];
                }
            }
        }];
        [self.chatTableView reloadData];
    }
    
    // 播放语音
    //    NSString *fileName = voiceMessage.path.lastPathComponent;
    //    NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //    doucument = [doucument stringByAppendingPathComponent:kMessageVoiceFileName];
    //    NSString *fullpath = [doucument stringByAppendingPathComponent:fileName];
    
    [[AudioPlayerHelper shareAudioPlayerHelper] startPlayerWithPath:fullpath model:voiceMessage completion:^(NSError * _Nonnull error) {
        voiceMessage.isPlaying = NO;
        [ws.chatTableView reloadData];
    }];
    voiceMessage.isPlaying = YES;
    [self.chatTableView reloadData];
}


#pragma mark - Send Message

// 发送文本
- (void)sendTextMessage:(NSString *)text {
    [self.chatBar clearInputViewText];
//    if (_chatType == ChatTypeGroup) {
//        if (!self.isOwnerOrManager) {
//            if (self.isForbid) {
//                [self showTipHudWithText:@"群已经开启禁言"];
//                return;
//            }
//        }
//    }
    if ([NSObject ldy_isEmpty:text]) {
        [self showTipHudWithText:@"请输入内容"];
        return;
    }
    self.originSendText = [text copy];
    NSString *idStr = @"";
    if (self.atType == 1) {
        idStr = [self.atIds componentsJoinedByString:@","];
    } else if (self.atType == 2) {
        idStr = kAtAllSymbols;
    }
    
    if (![NSObject ldy_isEmpty:idStr]) {
        text = [NSString stringWithFormat:@"%@%@%@", text, kAtDividedSymbols, idStr];
    }
    
    self.originSendText = [text copy];
    TextMessageModel *textModel = [TextMessageModel new];
    textModel.msgtype = MessageTypeText;
    textModel.messageDirection = MessageDirectionSend;
    textModel.fuuid = [LoginManager shareLoginManager].userModel.fuuid;
    textModel.f_uuid = [LoginManager shareLoginManager].userModel.fuuid;
    textModel.content = text;
    textModel.msg=text;
    long long timestamp =  [ChatTool shareChatTool].currentTimestamp;
    textModel.head = [LoginManager shareLoginManager].userModel.head;
    textModel.timestamp = timestamp;
    NSLog(@"当前时间戳=%lld",timestamp);
    if (self.chatType == ChatTypeFriend) {
        textModel.head = [LoginManager shareLoginManager].userModel.head;
        textModel.username = [LoginManager shareLoginManager].userModel.nickname;
    }else
    {
//        textModel.head = _groupHead;
//        textModel.username = _groupName;
        textModel.groupHead= self.markGroupHead;
        textModel.groupName= self.markGroupName;
    }
    
    textModel.rfuuid =  self.receiverId;
    textModel.chatType = self.chatType;
    textModel.gId = self.receiverId;
    textModel.nickname = [LoginManager shareLoginManager].userModel.nickname;
    textModel.username = [LoginManager shareLoginManager].userModel.nickname;
    textModel.messageStatus = MessageStatusDelivering;
    textModel.isAt = [NSObject ldy_isEmpty:idStr] ? NO : YES;
    KWeakSelf;
    [[LiftIMClient sharedClient].chatManager sendMessage:textModel complete:^(NSDictionary * _Nonnull info, NSError * _Nonnull error) {
        NSLog(@"发送之后返回=%@",info);
        if (!error) {
//            NSLog(@"发送成功=%@",info);
            NSArray *chatArray= info[@"chat"];
            [chatArray enumerateObjectsUsingBlock:^(NSDictionary * chatObj, NSUInteger idx, BOOL * _Nonnull stop) {
                //收消息成功
                textModel.clientuuid=[NSString stringWithFormat:@"%@",chatObj[@"clientuuid"]];
                textModel.createtime=[NSString stringWithFormat:@"%@",chatObj[@"createtime"]];
//                textModel.timestamp=[chatObj[@"createtime"] longLongValue];
//                发送时间
                textModel.msg_id=[NSString stringWithFormat:@"%@",chatObj[@"msg_id"]];
                textModel.uuid=[NSString stringWithFormat:@"%@",chatObj[@"uuid"]];
                textModel.type=[NSString stringWithFormat:@"%@",info[@"type"]];
                textModel.gidorfuuid=[NSString stringWithFormat:@"%@",info[@"gidorfuuid"]];
                //回执
            }];
            textModel.messageStatus = MessageStatusSucceed;
            [weakSelf.chatTableView reloadData];
            if (weakSelf.chatType==ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:textModel statusTo:MessageStatusSucceed];
            }else
            {
                [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:textModel statusTo:MessageStatusSucceed];
            }
        }else
        {
            NSLog(@"发送错误==%@",error);
//            [self showTipHudWithText:@"发送失败"];
            if ([info[@"code"] integerValue]==20001) {
                NSLog(@"您不在群里"); //群 被踢出群
//                textModel.msgtype=MessageTypeNotInGroup;
                [self addChatStateBefore:textModel msgtype:MessageTypeNotInGroup];
            }else if ([info[@"code"] integerValue]==20002)
            {
                NSLog(@"不是好友关系"); //单聊
//                textModel.msgtype=MessageTypeNotFriend;
                [self addChatStateBefore:textModel msgtype:MessageTypeNotFriend];

            }else if ([info[@"code"] integerValue]==20003)
            {
                NSLog(@"对方已经把你拉黑"); //单聊
//                textModel.msgtype=MessageTypeAddedBlacklist;
                [self addChatStateBefore:textModel msgtype:MessageTypeAddedBlacklist];

            }else if ([info[@"code"] integerValue]==20004)
            {
                NSLog(@"发送失败"); //单聊
//                textModel.msgtype=MessageTypeSendFailure;
                [self addChatStateBefore:textModel msgtype:MessageTypeSendFailure];
            }else if ([info[@"code"] integerValue]==20005)
            {
                [self addChatStateBefore:textModel msgtype:MessageTypeSendBanned];

            }
            textModel.messageStatus = MessageStatusFailed;
            [weakSelf.chatTableView reloadData];
            if (weakSelf.chatType==ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:textModel statusTo:MessageStatusFailed];
            } else {
                [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:textModel statusTo:MessageStatusFailed];
            }
        }
    }];
    textModel.content = self.originSendText;
    textModel.msg =self.originSendText;
    [self.chatTableView reloadData];
    [self addTimeMessageBefore:textModel];
    [self.dataSources addObject:textModel];
    //    [self sortedMessages];
    [self scrollToBottomRow];
    //存储数据
    [[ConversationListDataBase shareConversationListDataBase] saveConversation:textModel];
    [[ConversationManager shareManager] saveConversation:textModel];
   
    if (self.chatType ==ChatTypeFriend) {
        [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:textModel];
    } else {
        [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:textModel];
    }
    self.atType = 0;
    [_chatBar sendSuccessClearUserdata];
    [self.atIds removeAllObjects];

}

// 发送图片
- (void)sendImageMessage:(UIImage *)image {
    // 发送频率限制
    BOOL canSend = [self canSendMessages];
    if (!canSend) {
        [self showTipHudWithText:@"发送过于频繁，请稍后重试"];
        return;
    }
    ImageMessageModel *imageMessage = [ImageMessageModel new];
    imageMessage.image = image;
    imageMessage.width = SCREEN_WIDTH * 0.25;
    imageMessage.height = imageMessage.width * 1.5;
    imageMessage.msgtype = MessageTypeImage;
    imageMessage.messageDirection = MessageDirectionSend;
    //voice.content = [NSString stringWithFormat:@"%d,%@",timeLength, path];
    imageMessage.uid = [[LoginManager shareLoginManager].userModel.user_id integerValue];
    long long timestamp =  [ChatTool shareChatTool].currentTimestamp;
    imageMessage.avatar = [LoginManager shareLoginManager].userModel.head;
    imageMessage.timestamp = timestamp;
    imageMessage.cid = timestamp;
    imageMessage.mine = YES;
//    imageMessage.msgtype = MessageTypeImage;
    imageMessage.username = [LoginManager shareLoginManager].userModel.nickname;
    imageMessage.receiveUid = imageMessage.groupId = [self.receiverId integerValue];
//    imageMessage.type = self.type;
    imageMessage.fuuid = [LoginManager shareLoginManager].userModel.fuuid;
    imageMessage.f_uuid = [LoginManager shareLoginManager].userModel.fuuid;
    imageMessage.messageStatus = MessageStatusDelivering;
    imageMessage.head = [LoginManager shareLoginManager].userModel.head;

    if (self.chatType == ChatTypeFriend) {
        imageMessage.head = [LoginManager shareLoginManager].userModel.head;
        imageMessage.username = [LoginManager shareLoginManager].userModel.nickname;
    }else
    {
//        imageMessage.head = _groupHead;
//        imageMessage.username = _groupName;
        imageMessage.groupHead= self.markGroupHead;
        imageMessage.groupName= self.markGroupName;
    }
    imageMessage.rfuuid =  self.receiverId;
    imageMessage.chatType = self.chatType;
    imageMessage.gId = self.receiverId;
    imageMessage.nickname = [LoginManager shareLoginManager].userModel.nickname;
    KWeakSelf;
    [[LiftIMClient sharedClient].chatManager sendMessage:imageMessage complete:^(NSDictionary * _Nonnull info, NSError * _Nonnull error) {
         if (!error) {
             NSArray *chatArray= info[@"chat"];
             [chatArray enumerateObjectsUsingBlock:^(NSDictionary * chatObj, NSUInteger idx, BOOL * _Nonnull stop) {
                 //收消息成功
                 imageMessage.clientuuid=[NSString stringWithFormat:@"%@",chatObj[@"clientuuid"]];
                 imageMessage.createtime=[NSString stringWithFormat:@"%@",chatObj[@"createtime"]];
                 //                textModel.timestamp=[chatObj[@"createtime"] longLongValue];
                 //                发送时间
                 imageMessage.msg_id=[NSString stringWithFormat:@"%@",chatObj[@"msg_id"]];
                 imageMessage.uuid=[NSString stringWithFormat:@"%@",chatObj[@"uuid"]];
                 imageMessage.type=[NSString stringWithFormat:@"%@",info[@"type"]];
                 imageMessage.gidorfuuid=[NSString stringWithFormat:@"%@",info[@"gidorfuuid"]];
                 //回执
             }];
             imageMessage.messageStatus = MessageStatusSucceed;
             [weakSelf.chatTableView reloadData];
             if (weakSelf.chatType==ChatTypeFriend) {
                 [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:imageMessage statusTo:MessageStatusSucceed];
             }else
             {
                 [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:imageMessage statusTo:MessageStatusSucceed];
             }
         }else
         {
             [self showTipHudWithText:@"发送失败"];
             if ([info[@"code"] integerValue]==20001) {
                 NSLog(@"您不在群里"); //群 被踢出群
//                 imageMessage.msgtype=MessageTypeNotInGroup;
                 [self addChatStateBefore:imageMessage msgtype:MessageTypeNotInGroup];
             }else if ([info[@"code"] integerValue]==20002)
             {
                 NSLog(@"不是好友关系"); //单聊
//                 imageMessage.msgtype=MessageTypeNotFriend;
                 [self addChatStateBefore:imageMessage msgtype:MessageTypeNotFriend];
                 
             }else if ([info[@"code"] integerValue]==20003)
             {
                 NSLog(@"对方已经把你拉黑"); //单聊
//                 imageMessage.msgtype=MessageTypeAddedBlacklist;
                 [self addChatStateBefore:imageMessage msgtype:MessageTypeAddedBlacklist];
                 
             }else if ([info[@"code"] integerValue]==2004)
             {
                 NSLog(@"发送失败"); //单聊
//                 imageMessage.msgtype=MessageTypeSendFailure;
                 [self addChatStateBefore:imageMessage msgtype:MessageTypeSendFailure];
             }else if ([info[@"code"] integerValue]==20005)
             {
                 [self addChatStateBefore:imageMessage msgtype:MessageTypeSendBanned];
                 
             }
             imageMessage.messageStatus = MessageStatusFailed;
             [weakSelf.chatTableView reloadData];
             
             if (weakSelf.chatType==ChatTypeFriend) {
                 [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:imageMessage statusTo:MessageStatusFailed];
             } else {
                 [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:imageMessage statusTo:MessageStatusFailed];
             }
         }
        AAIMLog(@"发送图片== %@，错误==%@",info,error);
    }];
    [self addTimeMessageBefore:imageMessage];
    [self.dataSources addObject:imageMessage];
    //    [self sortedMessages];
    [self scrollToBottomRow];
    [[ConversationListDataBase shareConversationListDataBase] saveConversation:imageMessage];
    [[ConversationManager shareManager] saveConversation:imageMessage];
    if (self.chatType == ChatTypeFriend) {
        [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:imageMessage];
    } else {
        [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:imageMessage];
    }
  
}

// 发送语音
- (void)sendVoiceMessage:(NSString *)filePath timeLength:(NSInteger)timeLength {
//    self.isScrollBottom = YES;
//    // 发送频率限制
//    BOOL canSend = [self canSendMessages];
//    if (!canSend) {
//        [self showTipHudWithText:@"发送过于频繁，请稍后重试"];
//        return;
//    }
    VoiceMessageModel *voice = [VoiceMessageModel new];
    voice.duration = timeLength;
    voice.path = filePath;
    voice.msgtype = MessageTypeVoice;
    voice.messageType = MessageTypeVoice;
    voice.messageDirection = MessageDirectionSend;
    voice.content = [NSString stringWithFormat:@"%ld,%@",timeLength, filePath];
    voice.msg = [NSString stringWithFormat:@"%@", filePath];
    voice.fuuid = [LoginManager shareLoginManager].userModel.fuuid;
    voice.f_uuid = [LoginManager shareLoginManager].userModel.fuuid;
    voice.uid = [[LoginManager shareLoginManager].userModel.user_id integerValue];
    long long timestamp =  [ChatTool shareChatTool].currentTimestamp;
    voice.avatar = [LoginManager shareLoginManager].userModel.head;
//    voice.head = [LoginManager shareLoginManager].userModel.head;
    voice.timestamp = timestamp;
    voice.cid = timestamp;
    voice.mine = YES;
    voice.specialType = MessageTypeVoice;
//    voice.username = [LoginManager shareLoginManager].userModel.nickname;
    voice.head = [LoginManager shareLoginManager].userModel.head;
    if (self.chatType == ChatTypeFriend) {
        voice.head = [LoginManager shareLoginManager].userModel.head;
        voice.username = [LoginManager shareLoginManager].userModel.nickname;
    }else
    {
//        voice.head = _groupHead;
//        voice.username = _groupName;
        voice.groupName= self.markGroupHead;
        voice.groupHead= self.markGroupName;
    }
    voice.rfuuid =  self.receiverId;
    voice.chatType = self.chatType;
    voice.gId = self.receiverId;
//    voice.type = self.type;
    voice.nickname = [LoginManager shareLoginManager].userModel.nickname;
    voice.messageStatus = MessageStatusDelivering;
    KWeakSelf;
    [[LiftIMClient sharedClient].chatManager sendMessage:voice complete:^(NSDictionary * _Nonnull info, NSError * _Nonnull error) {
        if (!error) {
            NSLog(@"发送成功语音=info ： %@",info);
            NSArray *chatArray= info[@"chat"];
            [chatArray enumerateObjectsUsingBlock:^(NSDictionary * chatObj, NSUInteger idx, BOOL * _Nonnull stop) {
                //收消息成功
                voice.clientuuid=[NSString stringWithFormat:@"%@",chatObj[@"clientuuid"]];
                voice.createtime=[NSString stringWithFormat:@"%@",chatObj[@"createtime"]];
                //                textModel.timestamp=[chatObj[@"createtime"] longLongValue];
                //                发送时间
                voice.msg_id=[NSString stringWithFormat:@"%@",chatObj[@"msg_id"]];
                voice.uuid=[NSString stringWithFormat:@"%@",chatObj[@"uuid"]];
                voice.type=[NSString stringWithFormat:@"%@",info[@"type"]];
                voice.gidorfuuid=[NSString stringWithFormat:@"%@",info[@"gidorfuuid"]];
                //回执
            }];
            voice.messageStatus = MessageStatusSucceed;
            [weakSelf.chatTableView reloadData];
            if (weakSelf.chatType==ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:voice statusTo:MessageStatusSucceed];
            }else
            {
                [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:voice statusTo:MessageStatusSucceed];
            }
        }else
        {
            [self showTipHudWithText:@"发送失败"];
            if ([info[@"code"] integerValue]==20001) {
                NSLog(@"您不在群里"); //群 被踢出群
//                voice.msgtype=MessageTypeNotInGroup;
                [self addChatStateBefore:voice msgtype:MessageTypeNotInGroup];
            }else if ([info[@"code"] integerValue]==20002)
            {
                NSLog(@"不是好友关系"); //单聊
//                voice.msgtype=MessageTypeNotFriend;
                [self addChatStateBefore:voice msgtype:MessageTypeNotFriend];
                
            }else if ([info[@"code"] integerValue]==20003)
            {
                NSLog(@"对方已经把你拉黑"); //单聊
//                voice.msgtype=MessageTypeAddedBlacklist;
                [self addChatStateBefore:voice msgtype:MessageTypeAddedBlacklist];
                
            }else if ([info[@"code"] integerValue]==20004)
            {
                NSLog(@"发送失败"); //单聊
//                voice.msgtype=MessageTypeSendFailure;
                [self addChatStateBefore:voice msgtype:MessageTypeSendFailure];
            }else if ([info[@"code"] integerValue]==20005)
            {
                [self addChatStateBefore:voice msgtype:MessageTypeSendBanned];
            }
            voice.messageStatus = MessageStatusFailed;
            [weakSelf.chatTableView reloadData];
            if (weakSelf.chatType==ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] updateMessage:voice statusTo:MessageStatusFailed];
            } else {
                [[GroupMessageDataBase shareGroupMessageDataBase] updateMessage:voice statusTo:MessageStatusFailed];
            }
        }
    }];
    [self addTimeMessageBefore:voice];
    [self.dataSources addObject:voice];
    //    [self sortedMessages];
    [self scrollToBottomRow];
    [[ConversationListDataBase shareConversationListDataBase] saveConversation:voice];
    [[ConversationManager shareManager] saveConversation:voice];
    if (self.chatType ==ChatTypeFriend) {
        [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:voice];
    } else {
        [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:voice];
    }
}

// 发送消息撤回
- (void)sendRecallMessage:(NSIndexPath *)indexPath {
    self.isScrollBottom = YES;
    BTMessageModel *obj = self.dataSources[indexPath.item];
    BTMessageModel *recall = [BTMessageModel new];
    recall.msgtype = MessageTypeRecall;
    recall.messageDirection = MessageDirectionSend;
    recall.content = [NSString stringWithFormat:@"%@撤回了一条消息", [LoginManager shareLoginManager].userModel.userName];
    recall.uid =  [[LoginManager shareLoginManager].userModel.user_id integerValue];
    recall.toId = obj.messageDirection == MessageDirectionSend ? [LoginManager shareLoginManager].userModel.user_id : [NSString stringWithFormat:@"%ld", (long)obj.uid];
    recall.avatar = [LoginManager shareLoginManager].userModel.head;
    recall.timestamp = obj.timestamp;
    recall.cid = obj.timestamp;
    recall.mine = YES;
    recall.msgtype = MessageTypeRecall;
    recall.username = [LoginManager shareLoginManager].userModel.nickname;
    recall.receiveUid = recall.groupId = [self.receiverId integerValue];
//    recall.type = self.type;
   
    //    [self addTimeMessageBefore:recall];
    [self.dataSources removeObject:obj];
    [self.dataSources addObject:recall];
    [self sortedMessages];
    [self.chatTableView reloadData];
    // 聊天记录需要先删除原来的消息，再插入撤回的消息提示
    if (self.chatType == ChatTypeFriend) {
        [[ChatMessagesDataBase shareChatMessagesDataBase] deleteMessage:recall];
        [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:recall];
    } else {
        [[GroupMessageDataBase shareGroupMessageDataBase] deleteMessage:recall];
        [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:recall];
    }
    // 会话列表只需插入最新的撤回消息提示
    [[ConversationListDataBase shareConversationListDataBase] saveConversation:recall];
    [[ConversationManager shareManager] saveConversation:recall];
}

#pragma mark - 键盘通知

- (void)keyBoardWillShow:(NSNotification *)note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        [self.chatBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-keyBoardHeight + EMVIEWBOTTOMMARGIN);
        }];
    };
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation completion:^(BOOL finished) {
            [self scrollToBottomRow];
        }];
    } else {
        animation();
    }
}

- (void)keyBoardWillHide:(NSNotification *)note {
    
    
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        [self.chatTableView reloadData];
        [self.chatBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view);
        }];
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
    
}


- (void)sortedMessages {
    NSArray *array = [self.dataSources sortedArrayUsingComparator:^NSComparisonResult(BTMessageModel *msg1, BTMessageModel *msg2) {
        return msg1.timestamp > msg2.timestamp;
    }];
    self.dataSources = [NSMutableArray arrayWithArray:array];
}


/**
 限制发送频率
 */
- (BOOL)canSendMessages {
    return YES;
    
}


#pragma mark - IMChatManagerDelegate
// 接收到消息
- (void)messagesDidReceive:(NSArray<BTMessageModel *> *)messages {
    [messages enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self handleReceiveChatMessage:obj];
    }];
}

- (void)handleReceiveChatMessage:(BTMessageModel *)obj {
    if (obj.chatType==ChatTypeSystem) {
        if (obj.type_id == SystemMessageAuditJoinGroup || obj.type_id == SystemMessageDeleteGroupMember || obj.type_id == SystemMessageMemberExit || obj.type_id ==  SystemMessageDeleteGroup) {
        }else
        {
            return;
        }
    }
    if (self.chatType!=obj.chatType) {
        return;
    }
//    BOOL isCurrentChatting = (self.chatType==ChatTypeFriend&&[obj.f_uuid isEqualToString: self.receiverId]) || (self.chatType==ChatTypeGroup && [obj.gId isEqualToString:self.receiverId]);
 
    
    BOOL isCurrentChatting = (self.chatType==ChatTypeFriend&&[obj.f_uuid isEqualToString: self.receiverId]) || (self.chatType==ChatTypeGroup && [[NSString stringWithFormat:@"%@",obj.gId] isEqualToString:[NSString stringWithFormat:@"%@",self.receiverId]]);
    if (!isCurrentChatting) return;
    if (obj.msgtype == MessageTypeRecall) {
        
    }else
    {
        if (obj.chatType == ChatTypeGroup) {
            [[GroupMessageDataBase shareGroupMessageDataBase] updateAvatarWithUid:obj.uid avatar:obj.head];
        }else
        {
            [[ChatMessagesDataBase shareChatMessagesDataBase] updateAvatarWithUid:obj.rfuuid.integerValue avatar:obj.head];
        }
        [self addTimeMessageBefore:obj];
        [self.dataSources addObject:obj];
    }
    [self scrollToBottomRow];
    // 删除未读消息数
    [[ConversationListDataBase shareConversationListDataBase] clearUnreadCount:obj];
    [[ConversationManager shareManager] clearUnreadCount:obj];
}
#pragma mark - back
- (void) rightBtnDidClick:(UIButton *)sender{
    if (_chatType==ChatTypeFriend) {
        FriendChatSettingVC * chatSetVC = [[FriendChatSettingVC alloc]init];
        chatSetVC.friendModel = _friendModel;
        chatSetVC.delegate = self;
        [self.navigationController pushViewController:chatSetVC animated:YES];
    }else
    {
        GroupSetViewController* groupSetVC=[[GroupSetViewController alloc]init];
        groupSetVC.groupId=self.receiverId;
        groupSetVC.delegate = self;
        [self.navigationController pushViewController:groupSetVC animated:YES];
    }
    [self.chatBar.textView resignFirstResponder];

}

- (void)clearGroupChatHistory{
    [self.dataSources removeAllObjects];
    [self.chatTableView reloadData];
}

#pragma mark - getter
- (UITableView *)chatTableView {
    if (!_chatTableView) {
        _chatTableView = [[UITableView alloc] init];
        _chatTableView.delegate = self;
        _chatTableView.dataSource = self;
        _chatTableView.tableFooterView = [UIView new];
    }
    return _chatTableView;
}

- (NSMutableArray<BTMessageModel *> *)dataSources {
    if (!_dataSources) {
        _dataSources = [NSMutableArray new];
    }
    return _dataSources;
}
- (NSMutableArray *)atIds {
    if (!_atIds) {
        _atIds = [NSMutableArray new];
    }
    return _atIds;
}
-(NSMutableDictionary*)selectedUserData
{
    if (!_selectedUserData) {
        _selectedUserData=[NSMutableDictionary new];
    }
    return _selectedUserData;
}
- (UIMenuController *)menuController {
    if (!_menuController) {
        _menuController = [UIMenuController sharedMenuController];
    }
    return _menuController;
}

- (UIMenuItem *)recallMenuItem {
    if (!_recallMenuItem) {
        _recallMenuItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(recallMenuItemAction:)];
    }
    
    return _recallMenuItem;
}

- (UIMenuItem *)textCopyMenuItem {
    if (!_textCopyMenuItem) {
        _textCopyMenuItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(textCopyMenuItemAction:)];
    }
    return _textCopyMenuItem;
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
